using System;
using System.Collections.Generic;

namespace Bull.Core
{
    public sealed class Mediator {
        private readonly static Lazy<Mediator> _instance = new Lazy<Mediator>(()=> new Mediator()); 
        
        private readonly Dictionary<string, List<Action<object>>> _callbacks = new Dictionary<string, List<Action<object>>>();

        private Mediator() { }

        public static Mediator Instance {
            get { return _instance.Value; }
        }

        public void Register(string id, Action<object> action)
        {
            if(!_callbacks.ContainsKey(id)) 
                _callbacks[id] = new List<Action<object>>();
            _callbacks[id].Add(action);
        }

        public void Unregister(string id, Action<object> action) {
            _callbacks[id].Remove(action);

            if(_callbacks[id].Count == 0) {
                _callbacks.Remove(id);
            }
        }

        public void SendMessage(string id, object message) {
            _callbacks[id].ForEach(action => action(message));
        }
    }
}